//
//  STMonitorIndicatorView.m
//  GoldChampion
//
//  Created by Mac on 2018/4/14.
//  Copyright © 2018年 stoneobs@icloud.com. All rights reserved.
//

#import "STMonitorIndicatorView.h"
#import "STMonitorFileLogger.h"
#import "STMonitorLogFormatter.h"
#import "STMonitorHeader.h"
#define consoleViewFrame  CGRectMake(0, 0, 200, 200)
#define normalViewFrame  CGRectMake(0, 0, 50, 50)
@interface STMonitorIndicatorView()
@property(nonatomic, strong) STButton                     *consoleButton;
@property(nonatomic, assign) CGPoint                        originPoint;
@property(nonatomic, strong) UIView                     *consoleView;
@property(nonatomic, strong) UITextView                     *textView;
@property(nonatomic, strong) STMonitorFileLogger                     *logger;
@end
@implementation STMonitorIndicatorView

+ (STMonitorIndicatorView *)deflult{
    static STMonitorIndicatorView * deflut = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        deflut = [[STMonitorIndicatorView alloc] initWithFrame:normalViewFrame];
    });
    return deflut;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        __weak typeof(self) weakSelf =  self;
        self.logger = (id)[DDLog sharedInstance].allLoggers.firstObject;
        [self.logger setDidLogHandle:^(DDLogMessage *message) {
            [weakSelf didLogMessage:message];
        }];
        [self configSubView];
        [self configConsoleView];
    }
    return self;
}
#pragma mark --subView
- (void)configSubView{
    self.backgroundColor = [UIColor clearColor];
    self.right = UIScreenWidth - 15;
    self.top = 20;
    self.hidden = YES;
    __weak typeof(self) weakSelf =  self;
    STButton * consoleButton = [[STButton alloc] initWithFrame:self.bounds
                                                     title:@"Console"
                                                titleColor:[UIColor whiteColor]
                                                 titleFont:12
                                              cornerRadius:self.width / 2
                                           backgroundColor:FlatMint
                                           backgroundImage:nil
                                                     image:nil];
    consoleButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    self.consoleButton = consoleButton;
    [self.consoleButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedConsoleButton];
    }];
    [self addSubview:consoleButton];
    
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self];
    
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pangesHandle:)];
    [self addGestureRecognizer:pan];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotoDebugViewer)];
    tap.numberOfTapsRequired =  5;
    [self addGestureRecognizer:tap];

//    [UIView animateWithDuration:0.2 animations:^{
//        self.transform = CGAffineTransformMakeRotation(M_PI/2);
//    }];
    
    
    self.originPoint = self.center;
}
- (void)configConsoleView{

    UIView * view = [[UIView alloc] initWithFrame:consoleViewFrame];
    view.backgroundColor = [FlatMint colorWithAlphaComponent:0.5];
    self.consoleView = view;
    [self addSubview:view];
    CGFloat buttonWith = view.width / 3;
    __weak typeof(self) weakSelf =  self;
    STButton * backButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, buttonWith, 44)
                                                     title:@"收起"
                                                titleColor:FlatWhite
                                                 titleFont:14
                                              cornerRadius:0
                                           backgroundColor:nil
                                           backgroundImage:nil
                                                     image:nil];
    backButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [backButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedBackButton];
    }];
    [view addSubview:backButton];
    
    
    STButton * copyButton = [[STButton alloc] initWithFrame:CGRectMake(buttonWith, 0, buttonWith, 44)
                                                      title:@"复制"
                                                 titleColor:FlatWhite
                                                  titleFont:14
                                               cornerRadius:0
                                            backgroundColor:nil
                                            backgroundImage:nil
                                                      image:nil];
    copyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [copyButton setClicAction:^(UIButton *sender) {
        UIPasteboard *bord = [UIPasteboard generalPasteboard];
        [bord setString:weakSelf.textView.text];
        [SVProgressHUD showSuccessWithStatus:@"复制成功"];
    }];
    [view addSubview:copyButton];
    
    STButton * clearButton = [[STButton alloc] initWithFrame:CGRectMake(2*buttonWith, 0, buttonWith, 44)
                                                      title:@"清除"
                                                 titleColor:FlatWhite
                                                  titleFont:14
                                               cornerRadius:0
                                            backgroundColor:nil
                                            backgroundImage:nil
                                                      image:nil];
    clearButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [clearButton setClicAction:^(UIButton *sender) {
        weakSelf.textView.text = @"";
    }];
    [view addSubview:clearButton];
    
    UIView * line = [[UIView alloc] initWithFrame:CGRectMake(0, 45, view.width, 0.5)];
    line.backgroundColor = TM_lineColor;
    [view addSubview:line];
    [view st_setBorderWith:1 borderColor:FlatMint cornerRadius:5];
    
    
    [view addSubview:self.textView];
    
    self.consoleView.hidden = YES;
    [self addSubview:self.consoleView];
}
- (UITextView*)textView{
    if (!_textView) {
        _textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 45, self.consoleView.width, self.consoleView.height - 50)];
        _textView.text = @"";
        _textView.font = [UIFont systemFontOfSize:10];
       _textView.textColor = SecendTextColor;
    }
    return _textView;
}
#pragma mark --Public
- (void)updateConsoleState{
    bool open = [[NSUserDefaults standardUserDefaults] boolForKey:isOpenDeBugWindowKey];
    [UIView animateWithDuration:0.25 animations:^{
        self.hidden = !open;
    }completion:^(BOOL finished) {
        [self judgeEndPointAndDeal];
    }];
    
}
#pragma mark --Action Method
- (void)onSelctedConsoleButton{
    [UIView animateWithDuration:0.3 animations:^{
        self.consoleView.hidden = NO;
        self.consoleButton.hidden = YES;
        self.frame  = consoleViewFrame;
        self.center = self.originPoint;
    }completion:^(BOOL finished) {
        [self judgeEndPointAndDeal];
    }];

}
- (void)onSelctedBackButton{
    [UIView animateWithDuration:0.3 animations:^{
        self.consoleView.hidden = YES;
        self.consoleButton.hidden = NO;
        self.frame  = normalViewFrame;
        self.center = self.originPoint;
    }completion:^(BOOL finished) {
        [self judgeEndPointAndDeal];
    }];

}
- (void)pangesHandle:(UIPanGestureRecognizer*)pan{

    CGPoint point = [pan translationInView:self];
//    self.centerX   = self.originPoint.x + point.x;
//    self.centerY = self.originPoint.y + point.y;
    CGAffineTransform trance = self.transform;
    pan.view.transform =  CGAffineTransformTranslate(trance, point.x, point.y);
    [pan setTranslation:CGPointZero inView:pan.view];
    //DDLogDebug(@"手势拖动%@",NSStringFromCGPoint(point));
    if (pan.state == UIGestureRecognizerStateCancelled || pan.state == UIGestureRecognizerStateEnded) {
        
        [self judgeEndPointAndDeal];
    }
}
- (void)gotoDebugViewer{
    
    UIViewController  *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:[STMonitorHomeViewController new]];
    [rootViewController presentViewController:nav animated:YES completion:nil];
}
#pragma mark --Private Method
- (void)judgeEndPointAndDeal{
    CGFloat top = self.top - 0;
    CGFloat bootom = UIScreenHeight- self.bottom;
    CGFloat left = self.left - 0;
    CGFloat right = UIScreenWidth- self.right;
    CGFloat miny = MIN(top, bootom);
    CGFloat minx = MIN(left, right);
    CGFloat min = MIN(minx, miny);
    if (min == top ) {
        [UIView animateWithDuration:0.3
                              delay:0
             usingSpringWithDamping:0.7
              initialSpringVelocity:0.6
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^{
                             self.top = 15;
                             if (self.left < 0) {
                                 self.left = 15;
                             }
                             if (self.right > UIScreenWidth) {
                                 self.right = UIScreenWidth - 15;
                             }
                         } completion:^(BOOL finished) {
                             [self panGesEnd];
                         }];
    }
    
    if (min == left ) {
        [UIView animateWithDuration:0.3
                              delay:0
             usingSpringWithDamping:0.7
              initialSpringVelocity:0.6
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^{
                             self.left = 15;
                             if (self.top < 0) {
                                 self.top = 15;
                             }
                             if (self.bottom > UIScreenHeight) {
                                 self.bottom = UIScreenHeight - 15;
                             }
                         } completion:^(BOOL finished) {
                             [self panGesEnd];
                         }];
    }
    
    if (min == right ) {
        [UIView animateWithDuration:0.3
                              delay:0
             usingSpringWithDamping:0.7
              initialSpringVelocity:0.6
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^{
                             self.right = UIScreenWidth - 15;
                             if (self.top < 0) {
                                 self.top = 15;
                             }
                             if (self.bottom > UIScreenHeight) {
                                 self.bottom = UIScreenHeight - 15;
                             }
                         } completion:^(BOOL finished) {
                             [self panGesEnd];
                         }];
    }
    
    if (min == bootom ) {
        [UIView animateWithDuration:0.3
                              delay:0
             usingSpringWithDamping:0.7
              initialSpringVelocity:0.6
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^{
                             self.bottom = UIScreenHeight - 15;
                             if (self.left < 0) {
                                 self.left = 15;
                             }
                             if (self.right > UIScreenWidth) {
                                 self.right = UIScreenWidth - 15;
                             }
                         } completion:^(BOOL finished) {
                             [self panGesEnd];
                         }];
    }
}
- (void)panGesEnd{
    self.originPoint = self.center;
}
- (void)didLogMessage:(DDLogMessage*)message{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString * orginString = self.textView.text;
        NSString * delMessgae = [[STMonitorLogFormatter new] formatLogMessage:message];
        NSString * finsh = [NSString stringWithFormat:@"%@\n%@",orginString,delMessgae];
        self.textView.text = finsh;
    });

}
@end
